<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现购物车结算功能代码</title>
    <link rel="stylesheet" href="../css/style.css" />
    <script src="../js/cookie.js"></script>
    <script src="../js/ajax.js"></script>
    <script src="../js/interface.js"></script>
    <style>
        .w {
            width: 1200px;
            margin: 0 auto;
        }

        .tips {
            width: 1226px;
            margin: 0 auto;
        }

        .tips a {
            font-size: 14px;
        }

        .goods span {
            /* display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
            text-overflow: ellipsis; */

            display: -webkit-box;
            /** 对象作为伸缩盒子模型显示 **/
            -webkit-box-orient: vertical;
            /** 设置或检索伸缩盒对象的子元素的排列方式 **/
            -webkit-line-clamp: 2;
            /** 显示的行数 **/
            text-overflow: ellipsis;
            overflow: hidden;

        }
    </style>
</head>

<body>
    <div class="tips">
        <a href="./login.html">请登录</a>
        <a href="./register.html">免费注册</a>
    </div>
    <div class="w">
        <a href="./goodsList.html">商品列表</a>
    </div>
    <div class="catbox">
        <table id="cartTable">
            <thead>
                <tr>
                    <th><label>
                            <input class="check-all check" type="checkbox" />&nbsp;&nbsp;全选</label></th>
                    <th>商品</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>小计</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/1.jpg" alt="" /><span>Casio/卡西欧 EX-TR350</span></td>
                    <td class="price">5999.88</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">5999.88</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/2.jpg" alt="" /><span>Canon/佳能 PowerShot SX50 HS</span></td>
                    <td class="price">3888.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">3888.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/3.jpg" alt="" /><span>Sony/索尼 DSC-WX300</span></td>
                    <td class="price">1428.50</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">1428.50</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr>
                <tr>
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods"><img src="../images/4.jpg" alt="" /><span>Fujifilm/富士 instax mini 25</span></td>
                    <td class="price">640.60</td>
                    <td class="count"><span class="reduce"></span>
                        <input class="count-input" type="text" value="1" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">640.60</td>
                    <td class="operation"><span class="delete">删除</span></td>
                </tr> -->
            </tbody>
        </table>
        <div class="foot" id="foot">
            <a class="fl" id="deleteAll" href="javascript:;">删除</a>
            <div class="fr closing" onclick="getTotal();">结 算</div>
            <input type="hidden" id="cartTotalPrice" />
            <div class="fr total">合计：￥<span id="priceTotal">0.00</span></div>
            <div class="fr selected" id="selected">已选商品<span id="selectedTotal">0</span>件<span
                    class="arrow up">︽</span><span class="arrow down">︾</span></div>
            <div class="selected-view">
                <div id="selectedViewList" class="clearfix">
                    <div><img src="../images/1.jpg"><span>取消选择</span></div>
                </div>
                <span class="arrow">◆<span>◆</span></span>
            </div>
        </div>
    </div>
</body>
<script>
    // lgc 标识用户身份
    var tips = document.getElementsByClassName("tips")[0];
    var user = getCookie("lgc");
    if (user) {
        tips.innerHTML = `欢迎您,${user} <button onclick="exit()">退出</button>`
    }

    var catbox = document.getElementsByClassName("catbox")[0];
    var tbody = catbox.getElementsByTagName("tbody")[0];
    // searchShoppingCarByUser({user}).then().catch()


    loadShoppingCar();
    async function loadShoppingCar() {
        var result = await searchShoppingCarByUser({ user });
        console.log(result);
        var { status, detail, list } = result;
        if (status) {
            var html = "";
            list.forEach(({ id, gId, goodsName, goodsPrice, goodsImg, buyNum, total }) => {
                html += `<tr data-id="${id}">
                    <td class="checkbox"><input class="check-one check" type="checkbox" /></td>
                    <td class="goods">
                        <img src="${goodsImg}" alt="" />
                        <span>${goodsName}</span>
                    </td>
                    <td class="price">${goodsPrice}</td>
                    <td class="count"><span class="reduce">${buyNum > 1 ? "-" : ""}</span>
                        <input class="count-input" type="text" value="${buyNum}" />
                        <span class="add">+</span>
                    </td>
                    <td class="subtotal">${total}</td>
                    <td class="operation"><span class="delete" >删除</span></td>
                </tr>`
            })
            tbody.innerHTML = html;

        } else {
            tbody.innerHTML = "暂无商品 <a href='./goodsList.html'>采购商品</a>";
        }
    }


    var catbox = document.getElementsByClassName("catbox")[0];
    var checkAll = document.getElementsByClassName("check-all")[0];
    var checkOneList = document.getElementsByClassName("check-one");

    catbox.onclick = async function (e) {
        // console.log(11111);
        var e = e || window.event;
        var target = e.target || e.srcElement;
        // console.log(target);
        if (target.classList.contains("check-all")) {
            console.log("点击全选");
            checkAllHandler(target);
            getTotal();
        } else if (target.classList.contains("check-one")) {
            isAllChecked();
            getTotal();
        } else if (target.classList.contains("add")) {
            var parentTr = parent(parent(target));
            var id = parentTr.dataset.id;
            var result = await updateShoppingCarById({ id, type: 1 });
            var { status, detail } = result;
            if (status) {
                console.log("点击加号");
                addHandler(target);
                getTotal();
            } else {
                alert(detail);
            }

        } else if (target.classList.contains("reduce")) {

            var countInput = next(target);
            console.log(countInput);

            // a. 输入框  数量 减一 
            var num = countInput.value;

            // c.   减之前  判断  如果数量为1  不能减
            if (num <= 1) {
                return false; // 
            }

            var parentTr = parent(parent(target));
            var id = parentTr.dataset.id;
            var result = await updateShoppingCarById({ id, type: 0 });
            var { status, detail } = result;
            if (status) {
                console.log("点击加号");
                reduceHandler(target);
                getTotal();
            } else {
                alert(detail);
            }

        } else if (target.classList.contains("delete")) {
            deleteOneHandler(target);
            isAllChecked();
            getTotal();
        } else if (target.id == "deleteAll") {
            deleteAllHandler();
            isAllChecked();
            getTotal();
        }

    }

    function checkAllHandler(target) {
        var status = target.checked;
        console.log(status);
        for (var i = 0; i < checkOneList.length; i++) {
            var checkOne = checkOneList[i];
            checkOne.checked = status;
        }
    }
    function isAllChecked() {
        // 每次点击单选  判断所有的单选框是否全部被选中 
        var flag = true; // 假设全部被选中    =>  只要有一个没被选中即可推翻假设
        for (var j = 0; j < checkOneList.length; j++) {
            var checkOne = checkOneList[j];  // 获取每一个
            // console.log(checkOne);
            if (!checkOne.checked) {   // checkOne.checked == false   存在未被选中的
                flag = false;
                break;
            }
        }
        checkAll.checked = checkOneList.length == 0 ? false : flag;
    }

    async function addHandler(target) {
        // console.log(add, target);
        // console.log(target);      // 被点击的加号
        // target.previousElementSibling
        // debugger;

        //  (1) 商品数量加1 (被点击的加号前的)
        var countInput = prev(target);    // 被点击的加号 前的 countInp
        // console.log(countInput);
        var num = countInput.value;   // 取值 num
        num++;                        //自增
        countInput.value = num;       // 更新到页面

        // countInput.value++;

        // (2) 小计更新
        // target.parentElement
        var countTd = parent(target);   // 获取被点击加号的父元素

        var priceTd = prev(countTd);   // 找到父元素的前一个 
        var subtotalTd = next(countTd); // 

        var price = priceTd.textContent;
        var subtotal = num * price;

        console.log(price, subtotal);

        subtotalTd.textContent = subtotal.toFixed(2);


        //  减号按钮的 "-" 显示  
        var reduce = prev(countInput);
        reduce.textContent = "-";


    }
    function reduceHandler(target) {
        // console.log(target);
        var countInput = next(target);
        console.log(countInput);

        // a. 输入框  数量 减一 
        var num = countInput.value;

        // c.   减之前  判断  如果数量为1  不能减
        if (num == 1) {
            return false; // 
        }

        num--; // 自减

        if (num == 1) {
            target.textContent = "";
        }

        countInput.value = num;

        // b. 小计更新  =  单价*数量
        var parentTd = parent(target);
        var priceTd = prev(parentTd);
        var subtotalTd = next(parentTd);

        var price = priceTd.textContent * 1;

        var subtotal = price * num;

        subtotalTd.textContent = subtotal.toFixed(2);
    }
    async function deleteOneHandler(target) {
        if (confirm("是否删除该商品?")) {
            // target.remove();
            // var parentTd = parent(target);
            // var parentTr = parent(parentTd);
            var parentTr = parent(parent(target));
            // var id = parentTr.getAttribute("data-id");
            var id = parentTr.dataset.id;
            console.log(parentTr);

            var result = await deleteShoppingCarById({ id });
            var { status, detail } = result;
            if (status) {
                parentTr.remove();
            } else {
                alert(detail)
            }

        }
    }
    async function deleteAllHandler() {
        var list = [];
        for (let i = 0; i < checkOneList.length; i++) {
            let checkOne = checkOneList[i];
            if (checkOne.checked) {
                var parentTr = parent(parent(checkOne));
                var id = parentTr.dataset.id;
                list.push(id);
                console.log(parentTr);
                parentTr.remove();
                i--;
            }
        }
        console.log(list);

        var result = await deleteShoppingCarById({ id: list.join(",") });
        var { status, detail } = result;
        if (status) {
            alert(detail)
        } else {
            alert(detail)
        }

    }

    function getTotal() {
        // 只要涉及到购买的商品数量变化  都需要重新结算
        // 结算功能  => 找到所有选中状态的单选框 => 对应找出购买的商品的数量和小计  => 累加  => 输出
        console.log("结算中");
        var sum = 0;
        var allPrice = 0;
        for (let i = 0; i < checkOneList.length; i++) {
            let checkOne = checkOneList[i];
            if (checkOne.checked) {  // 如果单选框被选中
                var tr = parent(parent(checkOne));
                var countInput = tr.getElementsByClassName("count-input")[0];
                var subtotalTd = tr.getElementsByClassName("subtotal")[0];

                var num = countInput.value * 1;
                var subtotal = subtotalTd.textContent * 1

                sum += num;
                allPrice += subtotal;

            }
        }

        selectedTotal.textContent = sum;
        priceTotal.textContent = allPrice.toFixed(2);
    }




    function parent(ele) {
        return ele.parentElement || ele.parentNode;
    }

    function prev(ele) {
        return ele.previousElementSibling || ele.previousSibling;
    }

    function next(ele) {
        return ele.nextElementSibling || ele.nextSibling;
    }



    // eval("exit()")
    function exit() {
        delCookie("lgc");
        location.reload();
    }

</script>

</html>